/****************************************************
	文件：MeshBallBRDF.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/9/14 12:19:0
	功能：
*****************************************************/

using System;
using UnityEngine;

namespace LearningSRP
{
    public class MeshBallBRDF : MonoBehaviour
    {
        [Tooltip("生成个数")]
        public static int Count = 1023;

        private static int mBaseColorId = Shader.PropertyToID("_BaseColor");
        private static int mMetallicId = Shader.PropertyToID("_Metallic");
        private static int mSmoothnessId = Shader.PropertyToID("_Smoothness");
        private static int mCutoffId = Shader.PropertyToID("_Cutoff");
        [SerializeField, Tooltip("网格")]
        private Mesh mMesh = default;
        [SerializeField, Tooltip("材质")]
        private Material mMat = default;

        /// <summary>
        /// 平移、旋转、缩放 矩阵
        /// </summary>
        private Matrix4x4[] mMatrices = new Matrix4x4[Count];
        /// <summary>
        /// 各个 Instance 的颜色
        /// </summary>
        private Vector4[] mBaseColors = new Vector4[Count];
        /// <summary>
        /// 各个 Instance 的金属度
        /// </summary>
        private float[] mMetallics = new float[Count];
        /// <summary>
        /// 各个 Instance 的光滑度
        /// </summary>
        private float[] mSmoothnesss = new float[Count];
        /// <summary>
        /// Alpha裁剪阈值
        /// </summary>
        private float[] mCutoffs = new float[Count];
        /// <summary>
        /// 材质属性块
        /// </summary>
        private MaterialPropertyBlock mBlock;

        private void Awake()
        {
            for (int i = 0; i < mMatrices.Length; i++)
            {
                //创建 半径为10的 平移、旋转、缩放 矩阵
                mMatrices[i] = Matrix4x4.TRS(UnityEngine.Random.insideUnitSphere * 10f, Quaternion.identity, Vector3.one);
                //创建 随机颜色
                mBaseColors[i] = new Vector4(UnityEngine.Random.value, UnityEngine.Random.value, UnityEngine.Random.value, 1f);
                //创建 随机金属度
                mMetallics[i] = UnityEngine.Random.value;
                //创建 随机光滑度
                mSmoothnesss[i] = UnityEngine.Random.value;
                //创建 随机Alpha裁剪阈值
                mCutoffs[i] = UnityEngine.Random.value;
            }
        }
        private void Update()
        {
            if (mBlock == null)
            {
                mBlock = new MaterialPropertyBlock();
                mBlock.SetVectorArray(mBaseColorId, mBaseColors);
                mBlock.SetFloatArray(mMetallicId, mMetallics);
                mBlock.SetFloatArray(mSmoothnessId, mSmoothnesss);
                mBlock.SetFloatArray(mCutoffId, mCutoffs);
            }
            Graphics.DrawMeshInstanced(mMesh, 0, mMat, mMatrices, Count, mBlock);
        }
    }
}

